package com.changzhi.util;

import com.obs.services.ObsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;

/**
 * @Description:华为云上传工具
 * @author: 小落
 * @date: 2020年09月23日
 */
@Slf4j
@Component
public class ObsUtil {

	@Value("${huawei.obs.endpoint}")
	public String obsEndpoint;
	@Value("${huawei.obs.ak}")
	public String obsAk;
	@Value("${huawei.obs.sk}")
	public String obsSk;
	@Value("${huawei.obs.bucket}")
	public String obsBucket;
	@Value("${huawei.obs.domain}")
	public String obsDomain;
	@Value("${spring.profiles.active}")
	public String activeEnv;

	private static String endpoint;
	private static String ak;
	private static String sk;
	private static String bucket;
	private static String domain;
	private static String env;

	@PostConstruct
	public void init() {
		endpoint = this.obsEndpoint;
		ak = this.obsAk;
		sk = this.obsSk;
		bucket = this.obsBucket;
		domain = this.obsDomain;
		env = activeEnv;
	}

	public static String upload(String objPrefix, String objectName, InputStream is) {
		ObsClient obsClient = new ObsClient(ak, sk, endpoint);

		objPrefix = objPrefix.trim();
		if (objPrefix.isEmpty()) {
			objPrefix = "test/";
		}
		if (!objPrefix.endsWith("/")) {
			objPrefix += "/";
		}
		String objectPath = objPrefix + objectName;
		if (objectPath.startsWith("/")) { // objectKey不能以/开头
			objectPath = objectPath.substring(1);
		}
		log.info("To upload file into OBS, bucket:{} path:{}", bucket, objectPath);
		try {
			obsClient.putObject(bucket, objectPath, is);
			return domain + objectPath;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("method:uploadByUrl,objectPrefix={},objectName={},error:", objectPath, objectName, e.getMessage());
		}
		return null;
	}
}
